#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：pro1.py
@Author  ：beibei
@Date    ：2023/12/22 3:27 PM 
'''

import socket
import threading

# 存储消息的列表
messages = []

def handle_client(client_socket):
    while True:
        # 接收数据
        request = client_socket.recv(1024).decode('utf-8')
        if not request:
            break

        print(f"Received: {request}")
        action, *data = request.split(':')

        if action == 'push':
            # 推送消息
            messages.extend(data)
        elif action == 'pull':
            # 拉取消息
            client_socket.send(str(messages).encode('utf-8'))
            messages.clear()
        else:
            client_socket.send('Invalid action'.encode('utf-8'))

    client_socket.close()

def server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', 5000))
    server_socket.listen(5)
    print("Listening on port 5000...")

    while True:
        client, addr = server_socket.accept()
        print(f"Accepted connection from {addr}")
        client_handler = threading.Thread(target=handle_client, args=(client,))
        client_handler.start()

# 启动服务器
server()
